﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web.UI.WebControls;
using System.Collections;
using System.Drawing;
using Foxy.GridViewControls;
using System.Reflection;
using System.Web.UI;
#region License
//Copyright (c) 2008-2009 Edgar Iván Jaimes Martínez

//Permission is hereby granted, free of charge, to any person
//obtaining a copy of this software and associated documentation
//files (the "Software"), to deal in the Software without
//restriction, including without limitation the rights to use,
//copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the
//Software is furnished to do so, subject to the following
//conditions:

//The above copyright notice and this permission notice shall be
//included in all copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
//OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Foxy.WebControls
{
    [ToolboxData("<{0}:GridView ActivateRollOverColor='false' AutoGenerateColumns='false' runat='server'></{0}:GridView>")]
    public partial class GridView : System.Web.UI.WebControls.GridView
    {

        public GridView() { }

        #region Members overrides

        protected override ICollection CreateColumns(PagedDataSource dataSource, bool useDataSource)
        {
            ICollection columnList = base.CreateColumns(dataSource, useDataSource);
            if (!GenerateCheckBoxColumn)
                return columnList;

            // Add a checkbox column if required
            ArrayList extendedColumnList = AddCheckBoxColumn(columnList);
            return extendedColumnList;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // COMMENT: Add the script file
            Page.ClientScript.RegisterClientScriptResource(this.GetType(), "Foxy.Scripts.GridView.js");
        }

        protected override void OnRowDataBound(GridViewRowEventArgs e)
        {
            base.OnRowDataBound(e);
            GridViewRow row = e.Row;

            if (row.RowType == DataControlRowType.DataRow)
            {
                if (this.ActivateRollOverColor)
                {
                    row.Attributes["onmouseover"] =
                        String.Format("javascript:UpdateOverColor(this, '{0}','{1}'); this.style.cursor = 'hand';", 
                        ColorTranslator.ToHtml(this.RowRollOverColor),
                        ColorTranslator.ToHtml(this.RowRollOverText));
                    row.Attributes["onmouseout"] = "javascript:RestoreColor(this);";
                }
                Type t = row.DataItem.GetType();
                PropertyInfo property = t.GetProperty(this.CheckBoxDataField);
                CheckBox cb = (CheckBox)row.FindControl(CheckBoxItem.CheckBoxID);
                cb.Checked = (bool) property.GetValue(row.DataItem, null);

                // Get the appropriate style object for the row
                TableItemStyle style = GetRowStyleFromState(row.RowState);

                // Build the ID of the checkbox in the header
                string headerCheckBoxID = String.Format(CheckBoxColumHeaderID, ClientID);

                // Add script code to enable selection
                cb.Attributes["onclick"] = String.Format("ApplyStyle(this, '{0}', '{1}', '{2}', '{3}', '{4}', '{5}')",
                        ColorTranslator.ToHtml(SelectedRowStyle.ForeColor),
                        ColorTranslator.ToHtml(SelectedRowStyle.BackColor),
                        ColorTranslator.ToHtml(style.ForeColor),
                        ColorTranslator.ToHtml(style.BackColor),
                        (style.Font.Bold ? 700 : 400),
                        headerCheckBoxID);

                string argument = string.Empty;
                // Update the style of the checkbox if checked
                if (cb.Checked)
                {
                    row.BackColor = SelectedRowStyle.BackColor;
                    row.ForeColor = SelectedRowStyle.ForeColor;
                    row.Font.Bold = SelectedRowStyle.Font.Bold;
                }
                else
                {
                    row.BackColor = style.BackColor;
                    row.ForeColor = style.ForeColor;
                    row.Font.Bold = style.Font.Bold;
                }
                if (this.EnableAutoPostbackCheckBox) {
                    argument = String.Format("pb{0}", row.RowIndex.ToString());
                    cb.Attributes.Add("onclick", this.Page.ClientScript.GetPostBackEventReference(this, argument));
                }
                if (this.EnableRowClickEvent)
                {
                    argument = String.Format("click{0}", row.RowIndex.ToString());
                    row.Attributes.Add("onclick", this.Page.ClientScript.GetPostBackEventReference(this, argument));
                }
                if (this.EnableRowDoubleClickEvent)
                {
                    argument = String.Format("dclick{0}", row.RowIndex.ToString());
                    row.Attributes.Add("onDblClick", this.Page.ClientScript.GetPostBackEventReference(this, argument));
                }
            } 
        }

        protected override void LoadControlState(object savedState)
        {
            object[] objState = (object[])savedState;
            base.LoadControlState(objState[0]);
            this.GenerateCheckBoxColumn = (bool)objState[1];
            this.CheckBoxColumnIndex = (int)objState[2];
            this.EnableRowClickEvent = (bool)objState[3];
            this.EnableRowDoubleClickEvent = (bool)objState[4];
            this.ActivateRollOverColor = (bool)objState[5];
            this.EnableAutoPostbackCheckBox = (bool)objState[6];
        }

        protected override object SaveControlState()
        {
            object[] objR = { base.SaveControlState(), 
                              this.GenerateCheckBoxColumn,
                              this.CheckBoxColumnIndex,
                              this.EnableRowClickEvent,
                              this.EnableRowDoubleClickEvent,
                              this.ActivateRollOverColor,
                              this.EnableAutoPostbackCheckBox 
                            };
            return objR;
        }

        protected override void RaisePostBackEvent(string eventArgument)
        {
            int index = 0;
            
            if (eventArgument.StartsWith("click"))
            {
                index = int.Parse(eventArgument.Substring(5));
                RowClickEventArgs e = new RowClickEventArgs(this.Rows[index]);
                this.OnRowClick(e);
            }
            else if (eventArgument.StartsWith("dclick"))
            {
                index = int.Parse(eventArgument.Substring(6));
                RowDoubleClickEventArgs e = new RowDoubleClickEventArgs(this.Rows[index]);
                this.OnRowDoubleClick(e);
            }
            else if (eventArgument.StartsWith("pb"))
            {
                index = int.Parse(eventArgument.Substring(2));
                RowCheckedEventArgs e = new RowCheckedEventArgs(this.Rows[index]);
                this.OnCheckBoxCheckedChanged(e);
            }
            else
            {
                base.RaisePostBackEvent(eventArgument);
            }
        }

        protected override void OnRowEditing(GridViewEditEventArgs e)
        {
            base.OnRowEditing(e);
        }

        #endregion

    }
}
